/*
 * SerialHdl.c
 *
 * Created: 13.02.2013 22:42:08
 *  Author: victor
 */

/* Serial communication peripheral handler */

/* Module's includes */
#include <Basetypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <SerialHdl.h>
#include <CommonDefinitions.h>
/* Module's definitions */

/* Module's function definitions */

void SerialHdl_SendData ( u16 data )
{
	/* Clear global interrupts enable */
	SREG &= ~ ( 1 << SREG_I ); //cli();
	
	while ( ( UCSRA & ( 1 << UDRE ) ) == ZERO )
	{
		;
	}
	
	/* check if the 9th bit in the data to send is 1 or 0 */
	if ( data & 0x0100 )
	{
		/*set the 9th bit to be sent before UDR update*/
		UCSRB |= ( 1 << TXB8 );
	}
	
	else
	{
		/*set the 9th bit to be sent before UDR update*/
		UCSRB &= ~ ( 1 << TXB8 );
	}
	
	/*fill the UDR buffer with the rest of 8 bits of data to be sent*/
	UDR = ( u8 ) ( data & 0x00FF );
	
	/* Set the global interrupt enable bit */
	SREG |= ( 1 << SREG_I ); //sei();
	
}

/* Function that reads the incoming frameand is driven by Rx interrupt */
u16 SerialHdl_Getdata ( void )
{
	u16 tmp_data_u16;
	u8 tmp_LowByte_u8, tmp_HighByte_u8;
	/* store the value of the 9th bit of the frame before the last 8 bits! */
	tmp_HighByte_u8 = ( UCSRB & ( 1 << RXB8 ) ) >> 1;
	/* store the rest of 8 bits of received data */
	tmp_LowByte_u8 = UDR;
	/* concatenate the received data into a u16 variable to be used into the sw */
	tmp_data_u16 = ( ( u16 ) tmp_HighByte_u8 << 8 ) | ( tmp_LowByte_u8 );
	/* return the received value */
	return tmp_data_u16;
}